<template>

  <!-- 查询条件 -->
  <div>
    <el-form class="condition"
             :model="form"
             label-width="auto">
      <el-form-item label="商品ID">
        <el-input v-model="query.shopId" />
      </el-form-item>

      <el-form-item label="商品标题">
        <el-input v-model="query.title" />
      </el-form-item>

      <el-form-item label="厂商">
        <el-input v-model="query.makers" />
      </el-form-item>

      <el-form-item label="最大库存">
        <el-input v-model="query.num" />
      </el-form-item>

      <el-form-item label="最大成交">
        <el-input v-model="query.volume" />
      </el-form-item>

      <el-form-item label="最大价格">
        <el-input v-model="query.price" />
      </el-form-item>

      <el-form-item label="最大折扣">
        <el-input v-model="query.discount" />
      </el-form-item>

      <el-form-item label="状态">
        <el-radio-group v-model="query.statue">
          <el-radio value="1">已上架</el-radio>
          <el-radio value="0">已下架</el-radio>
          <el-radio value="-1">全部</el-radio>
        </el-radio-group>
      </el-form-item>

    </el-form>
    <el-form-item>
      <el-button type="primary"
                 @click="addShop"
                 v-if="user && user.role == 1">新增</el-button>
      <el-button type="primary"
                 @click="reqInfo">查询</el-button>
      <el-button @click="onResetSubmit">重置</el-button>
    </el-form-item>
  </div>

  <!-- 表格 -->
  <el-table :data="tableData"
            style="width: 100%">
    <el-table-column label="商品ID">
      <template #default="scope">
        <el-tag type="danger"> {{ scope.row.shopId }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="商品库存">
      <template #default="scope">
        {{ scope.row.num }}
      </template>
    </el-table-column>
    <el-table-column label="商品标题">
      <template #default="scope">
        {{ scope.row.title }}
      </template>
    </el-table-column>
    <el-table-column label="价格">
      <template #default="scope">
        {{ scope.row.price }}
      </template>
    </el-table-column>
    <el-table-column label="厂商">
      <template #default="scope">
        {{ scope.row.makers }}
      </template>
    </el-table-column>
    <el-table-column label="状态">
      <template #default="scope">
        <el-tag v-if="scope.row.statue == 1">{{ scope.row.statue == 1 ? "上架中" : "已下架" }}</el-tag>
        <el-tag v-else
                type="danger">{{ scope.row.statue == 1 ? "上架中" : "已下架" }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="折扣价">
      <template #default="scope">
        {{ scope.row.discount }}
      </template>
    </el-table-column>
    <el-table-column label="成交/单">
      <template #default="scope">
        {{ scope.row.volume ? scope.row.volume : 0 }}
      </template>
    </el-table-column>
    <el-table-column label="操作选项">
      <template #default="scope">
        <el-button v-if="user && user.role == 0"
                   size="small"
                   @click="handleBuy(scope.$index, scope.row)">
          购买
        </el-button>
        <div v-else>
          <el-button size="small"
                     @click="handleEdit(scope.$index, scope.row)">
            修改
          </el-button>
          <el-button size="small"
                     type="danger"
                     @click="handleDelete(scope.$index, scope.row)">
            删除
          </el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination v-model:current-page="query.page"
                 :pager-count="pageEvent.count"
                 layout="prev, pager, next"
                 :total="pageEvent.total"
                 @change="choosePage" />

  <!-- 商品信息弹窗 修改  新增 -->
  <el-dialog v-model="dialogFormVisible"
             title="商品信息修改"
             width="500">
    <el-form :model="form">
      <el-form-item label="编号">
        <el-input v-model="form.shopId"
                  disabled />
      </el-form-item>
      <el-form-item label="库存">
        <el-input v-model="form.num" />
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="form.price" />
      </el-form-item>
      <el-form-item label="折扣">
        <el-input v-model="form.discount" />
      </el-form-item>
      <el-form-item label="成交量">
        <el-input v-model="form.volume"
                  disabled />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.statue">
          <el-radio value="1">上架中</el-radio>
          <el-radio value="0">已下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="厂商">
        <el-input v-model="form.makers" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="propDisplay">取消</el-button>
        <el-button type="primary"
                   @click="propConfigm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script setup>
import { addShopInfo, selectShopInfo, buyShop, updateShopInfo, delShopInfo } from "@/api/index"
import { onMounted, ref, watch } from "vue"
import { ElMessage, ElMessageBox } from 'element-plus'

//用户信息
const user = ref({

})

//修改，新增弹窗控制
const dialogFormVisible = ref(false)

//新增、修改
const handleEdit = (index, row) => {
  //传递选中数据
  form.value = row
  form.value.statue += ''
  //打开弹窗
  dialogFormVisible.value = true
}

//监听弹窗点击取消
const propDisplay = () => {
  dialogFormVisible.value = false
}

//购买点击
const handleBuy = (index, row) => {
  ElMessageBox.confirm(
    '确认购买?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      //开始删除
      buyShop(row.shopId).then((res) => {
        console.log(res)
        if (res.data.code == 200 && res.data.data) {
          ElMessage({
            type: 'success',
            message: '购买成功',
          })
          //重新请求数据
          reqInfo()
        } else {
          ElMessage({
            type: 'info',
            message: '库存不足',
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

//监听分页选择
const choosePage = (e) => {
  query.value.page = e
  //重新请求数据
  reqInfo()
}

//新增按钮点击
const addShop = () => {
  dialogFormVisible.value = true
}

//监听弹窗点击确认
const propConfigm = () => {
  let queryValue = form.value
  dialogFormVisible.value
  if (form.value.statue != '') {
    queryValue.statue = parseInt(form.value.statue)
  }
  if (form.value.num != '') {
    queryValue.num = parseInt(form.value.num)
  }
  if (form.value.price != '') {
    queryValue.price = parseFloat(form.value.price)
  }
  if (form.value.discount != '') {
    queryValue.discount = parseFloat(form.value.discount)
  }
  //如果id不为空则是表明更新
  if (queryValue.shopId != '' || queryValue.shopId > 0) {
    updateShopInfo(queryValue).then((res) => {
      //查询成功，且有数据
      if (res.data.code == 200 && res.data.data) {
        //重新填充数据
        reqInfo()
      }
      ElMessage({
        message: res.data.msg,
        type: 'warning',
      })
      //初始化清空弹窗数据
      initProp();
      //关闭弹窗
      propDisplay()
    }).catch((err) => {
      console.log(err)
    })

    return
  }

  //新增
  addShopInfo(queryValue).then((res) => {
    console.log(res)
    //查询成功，且有数据
    if (res.data.code == 200 && res.data.data) {
      //重新填充数据
      reqInfo()
    }
    ElMessage({
      message: res.data.msg,
      type: 'warning',
    })
    //初始化弹窗
    initProp();
    //关闭弹窗
    propDisplay()
  }).catch((err) => {
    console.log(err)
  })

}

//底部分页数据内容
const pageEvent = ref({
  count: 5, //最大页码按钮数
  total: 100 //数据总量
})

//查询参数
const query = ref({
  page: 1,//当前第几页
  size: 10, //查询个数
  shopId: "",
  num: "",
  title: "",
  price: "",
  discount: "",
  volume: "",
  statue: "",
  makers: ""
})


//初始化查询参数
const initQuery = () => {
  query.value = {
    page: 1,//当前第几页
    size: 10, //查询个数
    shopId: "",
    num: "",
    title: "",
    price: "",
    discount: "",
    volume: "",
    statue: "",
    makers: ""
  }
}

//初始化弹窗
const initProp = () => {
  form.value = {
    shopId: "",
    num: "",
    title: "",
    price: "",
    discount: "",
    volume: "",
    statue: "",
    vendors: ""
  }
}

//删除
const handleDelete = (index, row) => {
  console.log(index, row)
  ElMessageBox.confirm(
    '确认删除该条数据吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      //开始删除
      delShopInfo(row.shopId).then((res) => {
        if (res.data.code == 200 && res.data.data) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          //重新请求数据
          reqInfo()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

//弹窗数据
const form = ref({
  shopId: "",
  num: "",
  title: "",
  price: "",
  discount: "",
  volume: "",
  statue: "",
  makers: ""
})

//条件清除
const onResetSubmit = () => {
  initQuery();
  //发起请求
  reqInfo()
}

//表格列表数据
const tableData = ref([])

//获取数据
const reqInfo = () => {
  let queryValue = query.value
  if (queryValue.num != '') {
    queryValue.num = parseInt(queryValue.num)
  }
  if (queryValue.price != '') {
    queryValue.price = parseFloat(queryValue.price)
  }
  if (queryValue.discount != '') {
    queryValue.discount = parseFloat(queryValue.discount)
  }
  selectShopInfo(queryString(queryValue)).then((res) => {
    //查询成功，且有数据
    if (res.data.code == 200 && res.data.data.total > 0) {
      tableData.value = []
      //重新填充数据
      tableData.value.push(...res.data.data.shop)
      //分页参数
      pageEvent.value.total = res.data.data.total
      return
    }
    ElMessage({
      message: res.data.msg,
      type: 'warning',
    })
  }).catch((err) => {
    console.log(err)
  })
}

//页面加载
onMounted(() => {
  //加载数据
  reqInfo()
  //获取用户信息
  user.value = JSON.parse(localStorage.getItem("user"))
})

// 请求参数处理
const queryString = (data) => {
  if (typeof data !== 'object' || data === null) {
    throw new Error('The input should be an object')
  }
  return (
    '?' +
    Object.keys(data)
      .map(
        (key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
      )
      .join('&')
  )
}

</script>


<style scoped>
.condition {
  display: flex;
  flex-wrap: wrap;
}

.condition:nth-child(n) {
  padding-right: 10px;
}
</style>